package demo.jwt;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

public abstract class JwtUtil {

	// second
	private static final long EXPIRE_TIME = 60*1000L;
	// 密钥
	private static final String TOKEN_SECRET = "123456";

	public static String genToken(Map<String, String> user) {

		String token = null;
		Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
		token = JWT.create().withIssuer("auth0").withClaim("user", user.get("user")).withExpiresAt(expiresAt)
				.sign(Algorithm.HMAC256(TOKEN_SECRET));

		return token;

	}

	public static Map<String, Object> parseToken(String token) {

		if (token == null) {
			return null;
		}

		JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
		// com.auth0.jwt.exceptions.TokenExpiredException: The Token has expired on Mon May 18 14:05:32 CST 2020.
		DecodedJWT jwt = verifier.verify(token);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("issuer", jwt.getIssuer());
		map.put("user", jwt.getClaim("user").asString());
		map.put("expiresAt", jwt.getExpiresAt());
		
		// map.put("claims", jwt.getClaims());


		return map;

	}

}